//
//  CHCameraSession.m
//  SCCAProofSdk
//
//  Created by cyptt on 2022/3/11.
//

#import "CHRecordData.h"
#import "CHCameraUitl.h"
#import "WCLRecordEncoder.h"
@interface CHRecordData()<AVCaptureVideoDataOutputSampleBufferDelegate,AVCaptureAudioDataOutputSampleBufferDelegate>{
    int _channels;//音频通道
    Float64 _samplerate;//音频采样率
}
@property(nonatomic,strong)AVCaptureSession * session;   //回话
@property(nonatomic,strong)AVCaptureDevice * captureDevice;  // 获取视频输入对象
@property(nonatomic,strong)AVCaptureDevice * audioDevice; //添加音频、话筒
@property(nonatomic,strong)AVCaptureDeviceInput * videoInput; // 根据输入设备初始化d设备输入对象，用于获得输入数据
@property(nonatomic,strong)AVCaptureDeviceInput  * audioInput; //音频、话筒输出


@property(nonatomic,strong)AVCaptureVideoDataOutput * videoOutput; //视频输出
@property (strong, nonatomic) AVCaptureAudioDataOutput   *audioOutput;//音频输出

@property(nonatomic,strong)AVCaptureConnection * videoConnection;  //视频链接

@property (strong, nonatomic) WCLRecordEncoder * recordEncoder;//录制编码

@property (copy  , nonatomic) dispatch_queue_t   captureQueue;//录制的队列

@end

@implementation CHRecordData


-(instancetype)init{
    if (self = [super init]) {
        [self config];
    }
    return self;
}


-(void)config{
    
}
-(AVCaptureSession *)getSession{
    return self.session;
}

-(void)start{
    dispatch_queue_t  queue = dispatch_queue_create("con.scca.test", DISPATCH_QUEUE_CONCURRENT);
    [self.videoOutput setSampleBufferDelegate:self queue:queue];
}
-(void)stop{
    [self.session stopRunning];
    [_recordEncoder finishWithCompletionHandler:^{
        NSLog(@"finish了----");
    }];
}




#pragma mark -- AVCaptureVideoDataOutputSampleBufferDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
     

    BOOL isVideo = YES;
    @synchronized (self) {
        if (output != self.videoOutput) {
            isVideo = NO;
        }
        
        if (self.recordEncoder == nil && !isVideo) {
            //初始化编码器，当音频和视频参数时创建编码器
            CMFormatDescriptionRef fmt = CMSampleBufferGetFormatDescription(sampleBuffer);
            [self setAudioFormat:fmt];
            NSString *defultPath = [CHCameraUitl getVideoPathCache];
            NSString *outputFielPath=[defultPath stringByAppendingPathComponent:[CHCameraUitl getVideoNameWithType:@"mp4"]];
            NSLog(@"视频保存地址%@",outputFielPath);
        //    NSURL *fileUrl=[NSURL fileURLWithPath:outputFielPath];
            self.videoPath = outputFielPath;
            self.recordEncoder = [WCLRecordEncoder encoderForPath:self.videoPath Height:1280 width:720 channels:_channels samples:_samplerate];
            
            NSLog(@"recordEncoder001===%@",self.recordEncoder);
           
        }
        // 增加sampleBuffer的引用计时,这样我们可以释放这个或修改这个数据，防止在修改时被释放
        CFRetain(sampleBuffer);
    }
   
    NSLog(@"self.recordEncoder======%@",self.recordEncoder);
    // 进行数据编码
    [self.recordEncoder encodeFrame:sampleBuffer isVideo:isVideo];
//    CFRelease(sampleBuffer);
    CFRelease(sampleBuffer);
}

//设置音频格式
-(void)setAudioFormat:(CMFormatDescriptionRef)fmt{
    const AudioStreamBasicDescription *asbd = CMAudioFormatDescriptionGetStreamBasicDescription(fmt);
    _samplerate = asbd->mSampleRate;
    _channels = asbd->mChannelsPerFrame;
}

- (void)captureOutput:(AVCaptureOutput *)output didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection API_AVAILABLE(ios(6.0), macCatalyst(14.0)) API_UNAVAILABLE(tvos){
    NSLog(@"002==%s",__func__);
}
    
#pragma mark --lazy
/*
 初始化会话
 */
-(AVCaptureSession *)session{
    if (!_session) {
        _session = [[AVCaptureSession alloc]init];
        [_session setSessionPreset:AVCaptureSessionPreset1280x720];
        
        //视频输入对象
        if (self.videoInput) {
          [_session addInput:self.videoInput];
        }

        //音频输入对象
        if (self.audioInput) {
            if ([_session canAddInput:self.audioInput]) {
                [_session addInput:self.audioInput];
            }
        }

        //将设备输出添加到会话中

        if ([_session canAddOutput:self.videoOutput]) {
            [_session addOutput:self.videoOutput];
        }

        if ([_session canAddOutput:self.audioOutput]) {
            [_session addOutput:self.audioOutput];
        }
        //捕捉连接
//        if ([self.videoConnection isVideoStabilizationSupported]) {
//            self.videoConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
///       }
        //设置录制方向
        self.videoConnection.videoOrientation = AVCaptureVideoOrientationPortrait;

    }
    return _session;
}
/*
 获取视频输入对象
 */
-(AVCaptureDevice *)captureDevice{
    if (!_captureDevice) {
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo ];
    }
    return  _captureDevice;
}

/*
 添加音频、话筒
 */

-(AVCaptureDevice *)audioDevice{
    if (!_audioDevice) {
        _audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio ];
    }
    return _audioDevice;
}
/*
 根据输入设备初始化d设备输入对象，用于获得输入数据 添加音频、话筒
 */
-(AVCaptureDeviceInput *)videoInput{
    if (!_videoInput) {
        NSError * error = nil;
        //根据输入设备初始化d设备输入对象，用于获得输入数据
        _videoInput =[AVCaptureDeviceInput deviceInputWithDevice:self.captureDevice error:&error];
       
    }
    return _videoInput;
}

/*
 音频输入
 */
-(AVCaptureDeviceInput *)audioInput{
    if (!_audioInput) {
        NSError * error = nil;
        _audioInput =[AVCaptureDeviceInput deviceInputWithDevice:self.audioDevice error:&error];
        if (error) {
            NSLog(@"获取麦克风失败~");
        }
    }
    return _audioInput;
}


/*
 视频输出
 */
-(AVCaptureVideoDataOutput *)videoOutput{
    if (!_videoOutput) {
        _videoOutput = [[AVCaptureVideoDataOutput alloc]init];
        [_videoOutput setAlwaysDiscardsLateVideoFrames:YES];
        
//        [_videoOutput setVideoSettings:@{(id)kCVPixelBufferPixelFormatTypeKey : [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]}];
        NSDictionary* setcapSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey,
                                        nil];
        _videoOutput.videoSettings = setcapSettings;
     
    }
    return _videoOutput;
}
/*
 音频输出
 */
- (AVCaptureAudioDataOutput *)audioOutput {
    if (_audioOutput == nil) {
        _audioOutput = [[AVCaptureAudioDataOutput alloc] init];
        [_audioOutput setSampleBufferDelegate:self queue:self.captureQueue];
    }
    return _audioOutput;
}

-(AVCaptureConnection *)videoConnection{
    if (!_videoConnection) {
        //设置录制模式
        _videoConnection = [self.videoOutput connectionWithMediaType:AVMediaTypeVideo];
      
    }
    return _videoConnection;
}

//录制的队列
- (dispatch_queue_t)captureQueue {
    if (_captureQueue == nil) {
        _captureQueue = dispatch_queue_create("cn.qiuyouqun.im.wclrecordengine.capture", DISPATCH_QUEUE_SERIAL);
    }
    return _captureQueue;
}
@end



